/* ========================================================================= */
/* ------------------------------------------------------------------------- */
/*!				\file		MainWindow.cc
				\date		june 2010
				\author		TNick

				\brief		Implements MainWindow class


	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	Please read ReadMe.txt and Licence.txt in root folder
	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


*/
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
//
//
//
//
/*  INCLUDES    ------------------------------------------------------------ */

#include	<QStyleFactory>

#include	"MainWindow.h"
#include	"Settings.h"

#include	<gui/prp/prpmdl.h>


/*  INCLUDES    ============================================================ */
//
//
//
//
/*  DEFINITIONS    --------------------------------------------------------- */

namespace	ACTD	{
	enum	ACT_TARG	{
			ACTT_THIS = 0,
			ASCTT_APP,
			ASCTT_MDI,

			ACTT_COUNT
		};
	struct	Act_Data	{
			ACT_TARG				targ;
			QStyle::StandardPixmap	std_icon; /* set to QStyle::SP_CustomBase to load from resource */
			const char*				pth_icon;
			QString					aName;
			QString					aTip;
			QKeySequence			aKey;
			const char*				slt;
		};
}	/* namespace ACTD */

namespace	STYSH	{
	enum	STY_TY	{
			STY_NONE = 0,	/* no style sheet */
			STY_FROMFILE,	/* load style sheet from file */
			STY_FROMFLD,	/* from style sheet folder */
			STY_MAX			/* boundary validation */
		};
}	/* namespace STYSH */


/*  DEFINITIONS    ========================================================= */
//
//
//
//
/*  DATA    ---------------------------------------------------------------- */

#include	"auto_actions.h"

/*  DATA    ================================================================ */
//
//
//
//
/*  FUNCTIONS    ----------------------------------------------------------- */



/* ------------------------------------------------------------------------- */
				MainWindow::MainWindow		(CC_Err* pErr, QWidget *parent) :
		QMainWindow(parent)
{
	pErr->Add(CCERR::EDEBUG_000, CCERR::CTX_GUI, 	__FUNCTION__);

	//StgsGui*	pStg;


	/* will be used to generate unique names */
	uiNewFileNr = 0;

	/* will be used to signal failed initialization */
	mdiArea = NULL;


	/* create a stgs object that is used for initialization */
	QSettings       stgs;
	stgs.beginGroup("MainWindow");

	/* load list of recent files */
	iMaxRecFiles = stgs.value("iMaxRecFiles", 10).toInt();
	slRecFiles = stgs.value("RecentFileList").toStringList();

	/* load saved state from stgs regarding main panel*/
	resize(
			stgs.value("size", QSize(400, 400)).toSize());
	move(
			stgs.value("pos", QPoint(200, 200)).toPoint());


	/* display the default name */
	setWindowTitle(tr("CASP. Powered by Qt and CGAL."));

	/* create and set-up central MDI area */
	mdiArea = new QMdiArea;
	if (mdiArea == NULL)
		{
			pErr->Add(CCERR::EERR_IN, CCERR::CTX_GUI,
					  tr("Main window initialization failed because of MDI"));
			goto Failed_Init;
		}
	mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
	mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
	setCentralWidget(mdiArea);
	connect(mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*)),
			this, SLOT(Slot_ActiveDraw(QMdiSubWindow*)));
	windowMapper = new QSignalMapper(this);
	connect(windowMapper, SIGNAL(mapped(QWidget*)),
			this, SLOT(Slot_ChangeActiveDraw(QWidget*)));







	// carete actions and menus
	if (!SUCCEDED(Init_Acts(pErr)))
		{
			pErr->Add(CCERR::EERR_IN, CCERR::CTX_GUI,
					  tr("Main window initialization failed because of actions"));
			goto Failed_Init;
		}
	if (!SUCCEDED(Init_Menus(pErr)))
		{
			pErr->Add(CCERR::EERR_IN, CCERR::CTX_GUI,
					  tr("Main window initialization failed because of menus"));
			goto Failed_Init;
		}
	if (!SUCCEDED(Init_Toolbars(pErr)))
		{
			pErr->Add(CCERR::EERR_IN, CCERR::CTX_GUI,
					  tr("Main window initialization failed because of toolbars"));
			goto Failed_Init;
		}
	if (!SUCCEDED(Init_Docks(pErr)))
		{
			pErr->Add(CCERR::EERR_IN, CCERR::CTX_GUI,
					  tr("Main window initialization failed because of docked panels"));
			goto Failed_Init;
		}


	// create a status bar
	statusBar()->showMessage(tr("Ready"));


	//pStg = new StgsGui();
	//pStg->exec();





	return;

	Failed_Init:
	pErr->Add(CCERR::EERR, CCERR::CTX_GUI,
			  tr("Main window initialization failed"));
	if (mdiArea != NULL)
		{
			mdiArea->close();
			delete mdiArea;
			mdiArea = NULL;
		}
	stgs.endGroup(); // MainWindow
	return;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
				MainWindow::~MainWindow		()
{

}
/* ========================================================================= */


/* ------------------------------------------------------------------------- */
CCERR::EERRORS	MainWindow::Init_Toolbars	(CC_Err* pErr)
{
	pErr->Add(CCERR::EDEBUG_000, CCERR::CTX_GUI, 	__FUNCTION__);



	prdTlb[PRD_TB::FILE] = addToolBar(tr("File"));
	if (prdTlb[PRD_TB::FILE] == NULL)
		{
			pErr->Add(CCERR::EERR_IN, CCERR::CTX_GUI,
					  tr("Toolbar initialization: File failed"));
			return CCERR::ERR_MALLOC;
		}
	prdTlb[PRD_TB::FILE]->addAction(prdAct[PRD_A::NEW]);
	prdTlb[PRD_TB::FILE]->addAction(prdAct[PRD_A::OPEN]);
	prdTlb[PRD_TB::FILE]->addAction(prdAct[PRD_A::SAVE]);
	prdTlb[PRD_TB::FILE]->addAction(prdAct[PRD_A::QUIT]);



	prdTlb[PRD_TB::EDIT] = addToolBar(tr("Edit"));
	if (prdTlb[PRD_TB::FILE] == NULL)
		{
			pErr->Add(CCERR::EERR_IN, CCERR::CTX_GUI,
					  tr("Toolbar initialization: Edit failed"));
			return CCERR::ERR_MALLOC;
		}
	prdTlb[PRD_TB::EDIT]->addAction(prdAct[PRD_A::UNDO]);
	prdTlb[PRD_TB::EDIT]->addAction(prdAct[PRD_A::REDO]);
	prdTlb[PRD_TB::EDIT]->addAction(prdAct[PRD_A::CUT]);
	prdTlb[PRD_TB::EDIT]->addAction(prdAct[PRD_A::COPY]);
	prdTlb[PRD_TB::EDIT]->addAction(prdAct[PRD_A::PASTE]);
	prdTlb[PRD_TB::EDIT]->addAction(prdAct[PRD_A::DELSEL]);



	prdTlb[PRD_TB::VIEW] = addToolBar(tr("View"));
	if (prdTlb[PRD_TB::FILE] == NULL)
		{
			pErr->Add(CCERR::EERR_IN, CCERR::CTX_GUI,
					  tr("Toolbar initialization: View failed"));
			return CCERR::ERR_MALLOC;
		}
	prdTlb[PRD_TB::VIEW]->addAction(prdAct[PRD_A::UNDO]);
	prdTlb[PRD_TB::VIEW]->addAction(prdAct[PRD_A::REDO]);
	prdTlb[PRD_TB::VIEW]->addAction(prdAct[PRD_A::CUT]);



	return CCERR::ERR_SUCCESS;
}
/* ========================================================================= */


/* ------------------------------------------------------------------------- */
CCERR::EERRORS	MainWindow::Init_Acts		(CC_Err* pErr)
{
	pErr->Add(CCERR::EDEBUG_000, CCERR::CTX_GUI, 	__FUNCTION__);

	QObject* target;

	/* create all actions from a table */
	for (int i = 0; i < PRD_A::MAX; i++)
		{
			switch	(Acts[i].targ)		{
			case	ACTD::ASCTT_MDI:	{
							target = mdiArea;
							break;}
			case	ACTD::ASCTT_APP:	{
					target = CC_App::appHeader();
							break;}
			default:					{
						target = this;
						break;}
			} /* switch	(Acts[i].targ) */

			/* action to create a new drawing */
			QIcon	ictouse;
			if (Acts[i].std_icon == QStyle::SP_CustomBase)
				{
					ictouse = QIcon(Acts[i].pth_icon);
				}
			else
				{
					ictouse = CC_App::appHeader()->style()->standardIcon(Acts[i].std_icon);
				}
			prdAct[i] = new QAction(
					ictouse,
					Acts[i].aName,
					this);
			if (prdAct[i] == NULL)
				{
					pErr->Add(CCERR::EERR_IN, CCERR::CTX_GUI,
							  tr("Actions initialization: Failed at index %1").arg(i));
					return CCERR::ERR_MALLOC;
				}
			prdAct[i]->setShortcut(QKeySequence(Acts[i].aKey));
			prdAct[i]->setStatusTip(Acts[i].aTip);
			connect(prdAct[i],
					SIGNAL(triggered()),
					target,
					Acts[i].slt);
		}

	return CCERR::ERR_SUCCESS;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
CCERR::EERRORS	MainWindow::Init_Docks		(CC_Err* pErr)
{
	pErr->Add(CCERR::EDEBUG_000, CCERR::CTX_GUI, 	__FUNCTION__);



	/* create explorer panel */
	prdDks[PRD_DK::EXPLORER] = new QDockWidget(tr("Explorer"), this);
	if (prdDks[PRD_DK::EXPLORER] == NULL)
		{
			pErr->Add(CCERR::EERR_IN, CCERR::CTX_GUI,
					  tr("Dock initialization: Failed at explorer"));
			return CCERR::ERR_MALLOC;
		}
	prdDks[PRD_DK::EXPLORER]->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
	QVBoxLayout *boxlay = new QVBoxLayout;
	QWidget *wi = new QWidget;
	wi->setLayout(boxlay);

	QStandardItemModel model_E(4, 4, prdDks[PRD_DK::EXPLORER]);
	for (int row = 0; row < 4; ++row) {
			for (int column = 0; column < 4; ++column) {
					QStandardItem *item = new QStandardItem(QString("row %0, column %1").arg(row).arg(column));
					model_E.setItem(row, column, item);
				}
		}
	view_E = new QTreeView(wi);
	//view_E->setModel(&model_E);
	view_E->setHeaderHidden(true);


	//// create toolbar that allows to change between views
	QToolBar*	explTb = new QToolBar(tr("expl_tb"), this);
	explTb->setAllowedAreas(Qt::AllToolBarAreas);
	explTb->setOrientation(Qt::Horizontal);
	explTb->setToolButtonStyle(Qt::ToolButtonIconOnly);
	explTb->setFloatable(false);
		QAction*	newAct;

		// create new items
		newAct = new QAction(tr("New"), this);
		// todo newAct->setShortcuts(QKeySequence::New);
		newAct->setStatusTip(tr("Create a new item"));
		newAct->setIcon(QIcon(":/res/tb_img/New_File.png"));
		//connect(newAct, SIGNAL(triggered()), this, SLOT(switchview_model()));
		explTb->addAction(newAct);

		// delete items
		newAct = new QAction(tr("Delete"), this);
		// todo newAct->setShortcuts(QKeySequence::New);
		newAct->setStatusTip(tr("Delete an existing item"));
		newAct->setIcon(QIcon(":/res/tb_img/Delete_Obj.png"));
		//connect(newAct, SIGNAL(triggered()), this, SLOT(switchview_model()));
		explTb->addAction(newAct);



	boxlay->addWidget(explTb);
	boxlay->addWidget(view_E);
	prdDks[PRD_DK::EXPLORER]->setWidget(wi);

	addDockWidget(Qt::RightDockWidgetArea, prdDks[PRD_DK::EXPLORER]);
	view_E->setVisible(true);
	prdMnu[PRD_M::VIEW]->addAction(prdDks[PRD_DK::EXPLORER]->toggleViewAction());





	/* create properties panel */
	prdDks[PRD_DK::PROP] = new QDockWidget(tr("Properties"), this);
	if (prdDks[PRD_DK::PROP] == NULL)
		{
			pErr->Add(CCERR::EERR_IN, CCERR::CTX_GUI,
					  tr("Dock initialization: Failed at properties"));
			return CCERR::ERR_MALLOC;
		}
	prdDks[PRD_DK::PROP]->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
	//QStandardItemModel model_P(4, 2, prdDks[PRD_DK::PROP]);
	//for (int row = 0; row < 4; ++row) {
	//		for (int column = 0; column < 2; ++column) {
	//				QStandardItem *item = new QStandardItem(QString("row %0, column %1").arg(row).arg(column));
	//				model_P.setItem(row, column, item);
	//			}
	//	}
	PrpMdl*	model_P = new PrpMdl();
//	PEX_Hd*	pNode1 = new PEX_Hd(
//		model_P,
//		NULL,
//		tr("Item 1"),
//		tr("description for item 1"));

//		PEX_bool*	pi_11 = new PEX_bool(
//			model_P,
//			pNode1,
//			tr("Item 11"),
//			tr("description for item 11"),
//			true);

//		PEX_Dbl*	pi_12 = new PEX_Dbl(
//			model_P,
//			pNode1,
//			tr("Item 12"),
//			tr("description for item 12"),
//			1.335);

//		QStringList fonts;
//		fonts << "Arial" << "Helvetica" << "Times" << "Courier";
//		PEX_Enum*	pi_13 = new PEX_Enum(
//			model_P,
//			pNode1,
//			tr("Item 13"),
//			tr("description for item 13"),
//			1,
//			fonts);



//	PEX_Hd*	pNode2 = new PEX_Hd(
//		model_P,
//		NULL,
//		tr("Item 2"),
//		tr("description for item 2"));

//		PEX_Col*	pi_21 = new PEX_Col(
//			model_P,
//			pNode2,
//			tr("Item 21"),
//			tr("description for item 21"),
//			qRgb(100,150,100));

//		PEX_Int*	pi_22 = new PEX_Int(
//			model_P,
//			pNode2,
//			tr("Item 22"),
//			tr("description for item 22"),
//			101);




//	PEX_Hd*	pNode3 = new PEX_Hd(
//		model_P,
//		NULL,
//		tr("Item 3"),
//		tr("description for item 3"));

//	PEX_Hd*	pNode4 = new PEX_Hd(
//		model_P,
//		NULL,
//		tr("Item 4"),
//		tr("description for item 4"));

//		PEX_Str*	pi_41 = new PEX_Str(
//			model_P,
//			pNode2,
//			tr("Item 41"),
//			tr("description for item 41"),
//			tr("String value"));




	view_P = new QTreeView(prdDks[PRD_DK::PROP]);
	view_P->setModel(model_P);
	prdDks[PRD_DK::PROP]->setWidget(view_P);
	addDockWidget(Qt::LeftDockWidgetArea, prdDks[PRD_DK::PROP]);
	view_P->setVisible(true);
	prdMnu[PRD_M::VIEW]->addAction(prdDks[PRD_DK::PROP]->toggleViewAction());







	/* create command panel */
	prdDks[PRD_DK::CMDOUT] = new QDockWidget(tr("Command"), this);
	if (prdDks[PRD_DK::CMDOUT] == NULL)
		{
			pErr->Add(CCERR::EERR_IN, CCERR::CTX_GUI,
					  tr("Dock initialization: Failed at command"));
			return CCERR::ERR_MALLOC;
		}
	prdDks[PRD_DK::CMDOUT]->setAllowedAreas(Qt::TopDockWidgetArea | Qt::BottomDockWidgetArea);
	QSplitter *splitter_C = new QSplitter(prdDks[PRD_DK::CMDOUT]);
	splitter_C->setOrientation(Qt::Vertical);
	prdDks[PRD_DK::CMDOUT]->setWidget(splitter_C);


	tx_out = new QTextEdit();
	tx_out->setReadOnly(true);
	splitter_C->addWidget(tx_out);
	tx_cmd = new QTextEdit();
	splitter_C->addWidget(tx_cmd);
	addDockWidget(Qt::BottomDockWidgetArea, prdDks[PRD_DK::CMDOUT]);
	prdMnu[PRD_M::VIEW]->addAction(prdDks[PRD_DK::CMDOUT]->toggleViewAction());






	return CCERR::ERR_SUCCESS;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
CCERR::EERRORS	MainWindow::Init_Menus		(CC_Err* pErr)
{
	QAction *   Act_loc;

	pErr->Add(CCERR::EDEBUG_000, CCERR::CTX_GUI, 	__FUNCTION__);

	prdMnu[PRD_M::FILE] = menuBar()->addMenu(tr("&File"));
	prdMnu[PRD_M::FILE]->addAction(prdAct[PRD_A::NEW]);
	prdMnu[PRD_M::FILE]->addAction(prdAct[PRD_A::OPEN]);
	prdMnu[PRD_M::F_RECENT] = new QMenu(tr("Recent files"));
	prdMnu[PRD_M::FILE]->addMenu(prdMnu[PRD_M::F_RECENT]);
	prdMnu[PRD_M::FILE]->addSeparator();
	prdMnu[PRD_M::FILE]->addAction(prdAct[PRD_A::SAVE]);
	prdMnu[PRD_M::FILE]->addAction(prdAct[PRD_A::SAVEAS]);
	prdMnu[PRD_M::FILE]->addSeparator();
	prdMnu[PRD_M::FILE]->addAction(prdAct[PRD_A::PRINT]);
	prdMnu[PRD_M::FILE]->addSeparator();
	prdMnu[PRD_M::FILE]->addAction(prdAct[PRD_A::CLOSE]);
	prdMnu[PRD_M::FILE]->addAction(prdAct[PRD_A::CLOSEALL]);
	prdMnu[PRD_M::FILE]->addAction(prdAct[PRD_A::QUIT]);
	if (slRecFiles.count() > 0)
		{
			for (int i = 0; i < slRecFiles.count(); i++)
				{
					Act_loc = new QAction(
							slRecFiles[i],
							this);
					Act_loc->setStatusTip(tr("Click to open this file"));
					connect(Act_loc,
							SIGNAL(triggered()),
							this,
							SLOT(Slot_open_recent()));
					prdMnu[PRD_M::F_RECENT]->addAction(Act_loc);
				}
		}
	else
		{
			prdMnu[PRD_M::F_RECENT]->setEnabled(false);
		}

	prdMnu[PRD_M::EDIT] = menuBar()->addMenu(tr("&Edit"));
	prdMnu[PRD_M::EDIT]->addAction(prdAct[PRD_A::UNDO]);
	prdMnu[PRD_M::EDIT]->addAction(prdAct[PRD_A::REDO]);
	prdMnu[PRD_M::EDIT]->addSeparator();
	prdMnu[PRD_M::EDIT]->addAction(prdAct[PRD_A::CUT]);
	prdMnu[PRD_M::EDIT]->addAction(prdAct[PRD_A::COPY]);
	prdMnu[PRD_M::EDIT]->addAction(prdAct[PRD_A::PASTE]);
	prdMnu[PRD_M::EDIT]->addAction(prdAct[PRD_A::DELSEL]);

	prdMnu[PRD_M::VIEW] = menuBar()->addMenu(tr("&View"));
	/* list of available skins */
	prdMnu[PRD_M::V_SKIN] = new QMenu(tr("S&kins"));
	connect(prdMnu[PRD_M::V_SKIN],
			SIGNAL(triggered(QAction*)),
			this,
			SLOT(Slot_ChangeSkin(QAction*)));
	QStringList	sty_list = QStyleFactory::keys();
	for (int i = 0; i < sty_list.count(); i++)
		{
			Act_loc = new QAction(
					sty_list.at(i),
					this);
			Act_loc->setData(i);
			Act_loc->setStatusTip(tr("Predefined skin"));
			Act_loc->setCheckable(true);
			if (CC_App::appHeader()->style()->objectName().compare(sty_list.at(i),Qt::CaseInsensitive))
				{ /* a value diffrent from 0 means this is not it */
					Act_loc->setChecked(false);
				}
			else
				{
					Act_loc->setChecked(true);
				}
			prdMnu[PRD_M::V_SKIN]->addAction(Act_loc);
		}
	prdMnu[PRD_M::VIEW]->addMenu(prdMnu[PRD_M::V_SKIN]);


	/* list of available style sheets */
	prdMnu[PRD_M::V_SSHEET] = new QMenu(tr("St&yle sheets"));

	connect(prdMnu[PRD_M::V_SSHEET],
			SIGNAL(triggered(QAction*)),
			this,
			SLOT(Slot_StyleSheet(QAction*)));
	prdMnu[PRD_M::VIEW]->addMenu(prdMnu[PRD_M::V_SSHEET]);
	Act_loc = new QAction( /* will remove any formatting */
			tr("None"),
			this);
	Act_loc->setStatusTip(tr("Unload any style sheets, leaving the application only with the skin"));
	Act_loc->setData(STYSH::STY_NONE);
	prdMnu[PRD_M::V_SSHEET]->addAction(Act_loc);
	Act_loc = new QAction(
			tr("Load ..."),
			this);
	Act_loc->setData(STYSH::STY_FROMFILE);
	Act_loc->setStatusTip(tr("Load a style sheet from a file"));
	prdMnu[PRD_M::V_SSHEET]->addAction(Act_loc);

	/* get style sheets folder */
	QDir	dir_ss(QCoreApplication::applicationFilePath());
	dir_ss.cd(QString("../StyleSheets"));
	if (dir_ss.exists())
		{
			QStringList filters;
			filters << "*.css";
			dir_ss.setNameFilters(filters);
			dir_ss.setFilter(QDir::NoDotAndDotDot | QDir::Files | QDir::Readable);
			filters = dir_ss.entryList();
			if (filters.count() > 0)
				{
					prdMnu[PRD_M::V_SSHEET]->addSeparator();/* --------------- */
					for (int i = 0; i < filters.count(); i++)
						{
							Act_loc = new QAction(
									filters.at(i),
									this);
							Act_loc->setStatusTip(tr("StyleSheet located in application's predefined folder"));
							Act_loc->setData(STYSH::STY_FROMFLD);
							prdMnu[PRD_M::V_SSHEET]->addAction(Act_loc);
						}
				}
		}
	prdMnu[PRD_M::VIEW]->addSeparator();


	prdMnu[PRD_M::WINDOW] = menuBar()->addMenu(tr("&Window"));
	prdMnu[PRD_M::WINDOW]->addAction(prdAct[PRD_A::TILE]);
	prdMnu[PRD_M::WINDOW]->addAction(prdAct[PRD_A::CASCADE]);
	prdMnu[PRD_M::WINDOW]->addAction(prdAct[PRD_A::NEXTMDI]);
	prdMnu[PRD_M::WINDOW]->addAction(prdAct[PRD_A::PREVMDI]);
	prdMnu[PRD_M::WINDOW]->addSeparator();

	prdMnu[PRD_M::HELP] = menuBar()->addMenu(tr("&Help"));
	prdMnu[PRD_M::HELP]->addAction(prdAct[PRD_A::ABOUT]);
	prdMnu[PRD_M::HELP]->addAction(prdAct[PRD_A::ABOUT_QT]);
	prdMnu[PRD_M::HELP]->addAction(prdAct[PRD_A::ABOUT_CGAL]);


	return CCERR::ERR_SUCCESS;
}
/* ========================================================================= */


/* ------------------------------------------------------------------------- */
void            MainWindow::closeEvent		(QCloseEvent *event)
{

	// attempt to close all MDI items
	mdiArea->closeAllSubWindows();

	// see if we have succeded
	if (mdiArea->currentSubWindow())
		{ // nope; can't close right now
			event->ignore();
		}
	else
		{ // yep; all are closed
			SaveSettings();
			event->accept();
		}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::SaveSettings	(void)
{
	QSettings settings;

	settings.beginGroup("MainWindow");
	settings.setValue("size", size());
	settings.setValue("pos", pos());
	settings.setValue("iMaxRecFiles", iMaxRecFiles);
	settings.setValue("RecentFileList", slRecFiles);
	settings.endGroup();
}
/* ========================================================================= */


/* ------------------------------------------------------------------------- */
void            MainWindow::Slot_ChangeActiveDraw		(QWidget *window)
{
	if (!window)
		return;
	mdiArea->setActiveSubWindow(qobject_cast<QMdiSubWindow *>(window));
}
/* ========================================================================= */


/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_ActiveDraw				(QMdiSubWindow* window)
{
	/* discard signals that simply tell we've got focus */
	if (p_active_draw == static_cast<MdiDraw*>(window))
		return;
	if (window == NULL)
		return;
	p_active_draw = static_cast<MdiDraw*>(window);

	/* load data from this drawing into the explorer */
	QAbstractItemModel* pPrevMdl = view_E->model();
	view_E->setModel(p_active_draw->getStdIModel());
	if (pPrevMdl != NULL)
		delete pPrevMdl;
	for (int i = 0; i < 3; i++)
	{
		view_E->resizeColumnToContents(i);
	}

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void            MainWindow::switchLayoutDirection		()
{
	if (layoutDirection() == Qt::LeftToRight)
		qApp->setLayoutDirection(Qt::RightToLeft);
	else
		qApp->setLayoutDirection(Qt::LeftToRight);
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_open					(void)
{

	QFileDialog::Options options;
	QString selectedFilter;
	QString fileName = QFileDialog::getOpenFileName(this,
													tr("Select drawing to open..."),
													QString(),
													tr("All Files (*);;Drawing Files (*.cas)"),
													&selectedFilter,
													options);
	if (!fileName.isEmpty())
		{
			AddRecentFile(fileName);
			NewDrawing(fileName);
		}

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_open_new				(void)
{
	NewDrawing(QString());
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_open_recent			(void)
{
	QAction *action = qobject_cast<QAction *>(sender());
	if (action)
		{
			NewDrawing(action->text());
		}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_save					(void)
{
	if (activeMdiChild() && activeMdiChild()->save())
		statusBar()->showMessage(tr("File saved"), 2000);
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_save_as				(void)
{

	QFileDialog::Options options;
	QString selectedFilter;
	QString fileName = QFileDialog::getSaveFileName(this,
													tr("Select drawing to open..."),
													QString(),
													tr("All Files (*);;Drawing Files (*.cas)"),
													&selectedFilter,
													options);
	if (!fileName.isEmpty())
		{
			if (activeMdiChild() && activeMdiChild()->saveAs())
				{
					statusBar()->showMessage(tr("File saved"), 2000);
					AddRecentFile(fileName);
				}
		}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_print					(void)
{


}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_undo					(void)
{


}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_redo					(void)
{


}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_cut					(void)
{
	//if (activeMdiChild())
	//	activeMdiChild()->drawing()->cut();

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_copy					(void)
{
	//if (activeMdiChild())
	//	activeMdiChild()->drawing()->copy();

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_paste					(void)
{
	//if (activeMdiChild())
	//	activeMdiChild()->drawing()->paste();

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_del					(void)
{
	//if (activeMdiChild())
	//	activeMdiChild()->drawing()->paste();

}
/* ========================================================================= */



/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_about					(void)
{
	//   QMessageBox::about(this, tr("About MDI"),
	//            tr("The <b>MDI</b> example demonstrates how to write multiple "
	//               "document interface applications using Qt."));
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::Slot_about_qt				(void)
{


}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void		MainWindow::Slot_about_cgal				(void)
{


}
/* ========================================================================= */


/* ------------------------------------------------------------------------- */
void		MainWindow::AddRecentFile		(QString sNewFile)
{
	/* check if is already in list (case sensitive!) */
	if (slRecFiles.count() > 0)
		{
			int i = slRecFiles.indexOf(sNewFile, 0);
			if (i != -1)
				{
					slRecFiles.move(i, 0);
					prdMnu[PRD_M::F_RECENT]->actions().move(i, 0);
					return;
				}
		}

	/* place this string in list */
	if (slRecFiles.count() >= iMaxRecFiles)
		{
			slRecFiles.removeAt(slRecFiles.count() - 1);
			/* remove the menu, too */
			prdMnu[PRD_M::F_RECENT]->actions().removeAt(slRecFiles.count() - 1);
		}
	slRecFiles.prepend(sNewFile);

	/* and create a menu entry for it */
	QAction *   Act_rec =
			new QAction(
					sNewFile,
					this);
	connect(Act_rec,
			SIGNAL(triggered()),
			this,
			SLOT(Slot_open_recent()));
	prdMnu[PRD_M::F_RECENT]->addAction(Act_rec);
	prdMnu[PRD_M::F_RECENT]->setEnabled(true);
}
/* ========================================================================= */






/* ------------------------------------------------------------------------- */
MdiDraw*		MainWindow::activeMdiChild	    ()
{
	if (QMdiSubWindow *activeSubWindow = mdiArea->activeSubWindow())
		return qobject_cast<MdiDraw *>(activeSubWindow->widget());
	return 0;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::updMenu		()
{
	bool hasMdiChild = (activeMdiChild() != 0);
	prdAct[PRD_A::SAVE]->setEnabled(hasMdiChild);
	prdAct[PRD_A::SAVEAS]->setEnabled(hasMdiChild);
	prdAct[PRD_A::CLOSE]->setEnabled(hasMdiChild);
	prdAct[PRD_A::CLOSEALL]->setEnabled(hasMdiChild);
	prdAct[PRD_A::CUT]->setEnabled(hasMdiChild);
	prdAct[PRD_A::COPY]->setEnabled(hasMdiChild);
	prdAct[PRD_A::PASTE]->setEnabled(hasMdiChild);
	prdAct[PRD_A::TILE]->setEnabled(hasMdiChild);
	prdAct[PRD_A::CASCADE]->setEnabled(hasMdiChild);
	prdAct[PRD_A::NEXTMDI]->setVisible(hasMdiChild);
	prdAct[PRD_A::PREVMDI]->setEnabled(hasMdiChild);

	updateWindowMenu();
	if (hasMdiChild)
		{
			//bool hasSelection = (activeMdiChild() &&
			//					 activeMdiChild()->drawing()->HasSelection());
			//prdAct[PRD_A::CUT]->setEnabled(hasSelection);
			//prdAct[PRD_A::COPY]->setEnabled(hasSelection);
		}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::updateWindowMenu	    ()
{
	prdMnu[PRD_M::WINDOW]->clear();
	prdMnu[PRD_M::WINDOW]->addAction(prdAct[PRD_A::TILE]);
	prdMnu[PRD_M::WINDOW]->addAction(prdAct[PRD_A::CASCADE]);
	prdMnu[PRD_M::WINDOW]->addSeparator();
	prdMnu[PRD_M::WINDOW]->addAction(prdAct[PRD_A::NEXTMDI]);
	prdMnu[PRD_M::WINDOW]->addAction(prdAct[PRD_A::PREVMDI]);
	prdMnu[PRD_M::WINDOW]->addSeparator();

	QList<QMdiSubWindow *> windows = mdiArea->subWindowList();

	for (int i = 0; i < windows.size(); ++i) {
			MdiDraw* child = qobject_cast<MdiDraw *>(windows[i]->widget());

			QString text;

			if (i < 9) {
					text = tr("&%1 %2").arg(i + 1).arg(child->name());
				} else {
						text = tr("%1 %2").arg(i + 1).arg(child->name());
					}
				QAction *action  = prdMnu[PRD_M::WINDOW]->addAction(text);
				action->setCheckable(true);
				action->setChecked(child == activeMdiChild());
				connect(action, SIGNAL(triggered()), windowMapper, SLOT(map()));
				windowMapper->setMapping(action, windows[i]);
			}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			MainWindow::newMDI					(MdiDraw* child)
{
	mdiArea->addSubWindow(child);
	//	connect(child, SIGNAL(copyAvailable(bool)),
	//			prdAct[PRD_A::CUT], SLOT(setEnabled(bool)));
	//	connect(child, SIGNAL(copyAvailable(bool)),
	//			prdAct[PRD_A::COPY], SLOT(setEnabled(bool)));
	return;
}
/* ========================================================================= */


/* ------------------------------------------------------------------------- */
void		MainWindow::NewDrawing					(QString sNewFile)
{
	/* first, check if this file is not loaded already */
	qDebug(sNewFile.toAscii());
	MdiDraw* pNewMdi = new MdiDraw(mdiArea, sNewFile);
	if (pNewMdi->InitOk())
		pNewMdi->show();
	else
		pNewMdi->close();
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void		MainWindow::Slot_ChangeSkin				(QAction * action)
{
	int	iIdx = action->data().toInt();

	QList<QAction*> lAct = prdMnu[PRD_M::V_SKIN]->actions();
	for (int i = 0; i < lAct.count(); i++)
		{
			lAct[i]->setChecked(false);
		}
	lAct[iIdx]->setChecked(true);
	CC_App::appHeader()->setStyle(action->text());
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void		MainWindow::Slot_StyleSheet				(QAction * action)
{
	STYSH::STY_TY	iIdx = (STYSH::STY_TY)action->data().toInt();
	CC_Err	LcErr;
	QString	FileToLoad;
	QString styleSheet;
	QFile css_file;

	switch	(iIdx)				{
	case	STYSH::STY_FROMFILE:{
					QFileDialog::Options options;
					QString selectedFilter;
					QString fileName = QFileDialog::getOpenFileName(this,
																	tr("Select style sheet to load ..."),
																	QString(),
																	tr("All Files (*);;Style sheets (*.css)"),
																	&selectedFilter,
																	options);
					if (!fileName.isEmpty())
						{
							FileToLoad = fileName;
							goto LoadAFile;
						}
					break;}
	case	STYSH::STY_FROMFLD:	{
					QDir	dir_ss(QCoreApplication::applicationFilePath());
					dir_ss.cd(QString("../StyleSheets"));
					if (dir_ss.exists())
						{
							FileToLoad = dir_ss.path() + "/" + action->text();
							if (dir_ss.exists(action->text()))
								{
									goto LoadAFile;
								}
							else
								{
									LcErr.Add(CCERR::EERR_IN, CCERR::CTX_GUI,
											  tr("File %1 was not found.").arg(FileToLoad));
									goto NoStyleSheet;
								}
						}
					else
						{
							LcErr.Add(CCERR::EERR_IN, CCERR::CTX_GUI,
									  tr("Folder %1 was not found.").arg(dir_ss.path()));
							goto NoStyleSheet;
						}
					break;}
	default:/*STYSH::STY_NONE:*/{
				CC_App::appHeader()->setStyleSheet(QString());
				break;}
}


	return;
	LoadAFile:
	/* read file content */
	css_file.setFileName(FileToLoad);
	if (!css_file.open(QFile::ReadOnly))
		goto NoStyleSheet;
	styleSheet = QLatin1String(css_file.readAll());
	css_file.close();

	/* and load it's content */
	CC_App::appHeader()->setStyleSheet(styleSheet);
	return;

	NoStyleSheet:
	LcErr.Add(CCERR::EERR, CCERR::CTX_GUI,
			  tr("Failed to load style sheet. The file does not exist."));
	LcErr.Show();
	return;
}
/* ========================================================================= */


/*  FUNCTIONS    =========================================================== */
//
//
//
//
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
